package com.javaforever.gatescore.gui;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.javaforever.gatescore.core.FileCopyer;
import org.javaforever.gatescore.core.FrontPrism;
import org.javaforever.gatescore.core.FrontProject;
import org.javaforever.gatescore.core.ValidateInfo;
import org.javaforever.gatescore.core.ZipCompressor;
import org.javaforever.gatescore.exception.ValidateException;
import org.javaforever.gatescore.utils.StringUtil;
import org.javaforever.gatescore.vue.DevEnvJs;
import org.javaforever.gatescore.vue.ElementUIHomePage;
import org.javaforever.gatescore.vue.EnJs;
import org.javaforever.gatescore.vue.ProdEnvJs;
import org.javaforever.gatescore.vue.SitEnvJs;
import org.javaforever.gatescore.vue.VuePageVars;
import org.javaforever.gatescore.vue.VueRouter;

public class JarProjectExportUtil {
	public static void generateProjectFiles(FrontProject project) throws Exception {
		ValidateInfo info = project.validate();
		if (info.success() == false) {
			throw new ValidateException(info);
		}
		project.decorateUserControllers();
		project.decorateMentuItems();
		String srcfolderPath = project.getFolderPath()+project.getStandardName()+"FrontEnd/";
		if (project.getSgsSource() != null && !project.getSgsSource().equals("")) {
			writeToFile(srcfolderPath + "sgs/" + StringUtil.capFirst(project.getStandardName()) + "_original.sgs",
					project.getSgsSource());
		}
	
		FileCopyer copy = new FileCopyer();
		
		if (!StringUtil.isBlank(project.getExcelTemplateName())){				
			File mF1 = new File((project.getExcelTemplateFolder()+project.getExcelTemplateName()).replace("\\", "/"));
			File mF2 = new File((srcfolderPath+ "exceltemplate/"+project.getExcelTemplateName()).replace("\\", "/"));
			if (mF1.exists()){
				if (!mF2.getParentFile().exists()){
					mF2.getParentFile().mkdirs();
				}
				if (!mF2.exists()){
					mF2.createNewFile();
				}
				copy.copy(mF1.getPath(), mF2.getPath());
			}
		}	
		TemplatesResourceCopyer tcopy = new TemplatesResourceCopyer();
		tcopy.downloadUnpackTemplates(project.getFolderPath()+project.getStandardName()+"FrontEnd/");
		
		EnJs enjs = new EnJs();
		enjs.setStanadardName(project.getStandardName());
		writeToFile(srcfolderPath + "src/lang/en.js",
				enjs.generateStatementList().getContent());
		
		DevEnvJs devenvjs = new DevEnvJs();
		devenvjs.setUseController(project.isUseController());
		devenvjs.setShowBackendProject(project.isShowBackendProject());
		devenvjs.setBackendProjectName(project.getBackendProjectName());
		writeToFile(srcfolderPath + "config/"+devenvjs.getFileName(),
				devenvjs.generateStatementList().getContent());
		
		SitEnvJs sitenvjs = new SitEnvJs();
		sitenvjs.setUseController(project.isUseController());
		sitenvjs.setShowBackendProject(project.isShowBackendProject());
		sitenvjs.setBackendProjectName(project.getBackendProjectName());
		writeToFile(srcfolderPath + "config/"+sitenvjs.getFileName(),
				sitenvjs.generateStatementList().getContent());
		
		ProdEnvJs prodenvjs = new ProdEnvJs();
		prodenvjs.setUseController(project.isUseController());
		prodenvjs.setShowBackendProject(project.isShowBackendProject());
		prodenvjs.setBackendProjectName(project.getBackendProjectName());
		writeToFile(srcfolderPath + "config/"+prodenvjs.getFileName(),
				prodenvjs.generateStatementList().getContent());
		
		ElementUIHomePage hpage = new ElementUIHomePage();
		hpage.setLanguage(project.getLanguage());
		writeToFile(srcfolderPath + "src/views/pages/index.vue",
				hpage.generateStatementList().getContent());
		for (FrontPrism ps : project.getPrisms()) {
			ps.setFolderPath(srcfolderPath);
			ps.generatePrismFiles();
		}
		VuePageVars pv = new VuePageVars();
		pv.setDomains(project.getDomains());
		writeToFile(srcfolderPath +"src/" +pv.getFileName(),
				pv.generateStatementList().getContent());
		
		VueRouter vr = new VueRouter();
		vr.setDomains(project.getDomains());
		for (FrontPrism fp:project.getPrisms()) {
			vr.addMtms(fp.getManyToManies());
		}
		writeToFile(srcfolderPath + "src/router/modules/"+vr.getFileName(),
				vr.generateStatementList().getContent());
	}
	
	
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void generateProjectZip(FrontProject project) throws Exception{
		String rootFolder = project.getFolderPath();
		rootFolder = rootFolder.replace("\\", "/");
		String zipFolder = rootFolder;
		if (rootFolder.contains("/")) {
			zipFolder = rootFolder.substring(0, rootFolder.lastIndexOf("/"));
			zipFolder = zipFolder + "/"+project.getStandardName()+"FrontEnd/";
		}else{
			throw new ValidateException("输出文件夹错误");
		}
		project.setFolderPath(rootFolder);
		
		delAllFile(project.getFolderPath()+project.getStandardName()+"FrontEnd.zip");
		delFolder(zipFolder);
		File f = new File(zipFolder);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.mkdirs();
				
		generateProjectFiles(project);
		ZipCompressor compressor = new ZipCompressor(rootFolder+project.getStandardName()+"FrontEnd.zip");
		compressor.compressExe(zipFolder);
		delFolder(zipFolder);
	}
	
	public  static void writeToFile(String filePath, String content) throws Exception{
		File f = new File(filePath);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.createNewFile();
		try (Writer fw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(f.getAbsolutePath()),"UTF-8"))){			
	        fw.write(content,0,content.length());
		}
	}

}
